package com.example.controller;

import com.example.common.Result;
import com.example.entity.Messages;
import com.example.service.MessagesService;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/messages")
public class MessagesController {
    @Resource
    MessagesService messagesService;

    @PutMapping("/read")
    public Result updateReadStatus() {
        // 设置当前的用户所有的消息通知为已读状态
        messagesService.updateReadStatus();
        return Result.success("标位已读状态成功");
    }

    @GetMapping("/unread")
    public Result unread(Messages messages) {
        Integer userId = TokenUtils.getCurrentUser().getId();
        if (userId != null) {
            messages.setIsRead(0);
            messages.setUserId(userId);
            // 查询当前登录用户所有未读的消息
            return Result.success("获取未读消息成功",messagesService.selectAll(messages));
//            return Result.success(messagesService.list(new QueryWrapper<Messages>().eq("user_id", user.getId()).eq("isread", 0)));
        } else {
            return Result.success("暂时没有新消息",Collections.EMPTY_LIST);
        }
    }

    @GetMapping("/selectAll")
    public Result selectAll(Messages messages) {
        List<Messages> list = messagesService.selectAll(messages);
        return Result.success("查询消息列表成功",list);
    }

    @GetMapping("/selectPage")
    public Result selectPage(Messages messages,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Messages> list = messagesService.selectPage(messages, pageNum, pageSize);
        return Result.success("分页查询消息列表成功",list);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Messages message = messagesService.selectById(id);
        return Result.success("查询消息成功",message);
    }

    @DeleteMapping("delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        messagesService.deleteById(id);
        return Result.success("删除消息成功");
    }

    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        messagesService.deleteBatch(ids);
        return Result.success("删除消息成功");
    }
    @PostMapping("/addMessage")
    public Result addMessage(@RequestBody Messages messages){
        messagesService.addMessage(messages);
        return Result.success("发送审核未通过原因成功");
    }
}
